package org.dark.fund.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.dark.fund.consts.FundSysConsts.TOKEN_HEADER;

@Slf4j
public class HttpTokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest && servletResponse instanceof HttpServletResponse) {
            doHttpFilter((HttpServletRequest) servletRequest, (HttpServletResponse) servletResponse, filterChain);
        }
    }

    /**
     * servletResponse响应头中若不含token,则将请求头的token加入其中
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    protected void doHttpFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String token = servletRequest.getHeader(TOKEN_HEADER);
        log.info("begin token: {}", token);
        // 无法修改请求完成后的响应头中的token, 别问为啥,问就是提交了
        servletResponse.setHeader(TOKEN_HEADER, token);
//        servletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:8081");
//        servletResponse.setHeader("Access-Control-Allow-Credentials", "true");


        filterChain.doFilter(servletRequest, servletResponse);
        log.info("end token: {}", servletResponse.getHeader(TOKEN_HEADER));
    }

}
